package org.jeecg.modules.activities.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.activities.entity.FhActenroll;
import org.jeecg.modules.activities.entity.FhActive;
import org.jeecg.modules.activities.entity.FhPicwall;
import org.jeecg.modules.activities.service.IFhActenrollService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.activities.service.IFhActiveService;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 日程报名
 * @Author: jeecg-boot
 * @Date:   2024-07-16
 * @Version: V1.0
 */
//@Api(tags="203日程报名")
@RestController
@RequestMapping("/activities/fhActenroll")
@Slf4j
public class FhActenrollController extends JeecgController<FhActenroll, IFhActenrollService> {
	@Autowired
	private IFhActenrollService fhActenrollService;

	 @Autowired
	 private IFhActiveService fhActiveService;

	@Value("${jeecg.path.upload}")
	private String upLoadPath;
	/**
	 * 分页列表查询
	 *
	 * @param fhActenroll
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "日程报名-分页列表查询")
	@ApiOperation(value="日程报名-分页列表查询", notes="日程报名-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<FhActenroll>> queryPageList(FhActenroll fhActenroll,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Integer isEnroll =1;//默认已报名
		if(oConvertUtils.isNotEmpty(fhActenroll.getIsEnroll())){
			isEnroll = fhActenroll.getIsEnroll()?1:0;
			fhActenroll.setIsEnroll(null);
		}
		Page<FhActenroll> page = new Page<FhActenroll>(pageNo, pageSize);
		if(isEnroll==1) {//已报名
			QueryWrapper<FhActenroll> queryWrapper = QueryGenerator.initQueryWrapper(fhActenroll, req.getParameterMap());
			IPage<FhActenroll> pageList = fhActenrollService.page(page, queryWrapper);
			return Result.OK(pageList);
		}else{
			if(oConvertUtils.isEmpty(fhActenroll.getParentId())){
				return Result.error("请选择活动！");
			}
			Map<String,Object> map = new HashMap<>();
			map.put("parentId",fhActenroll.getParentId());
			List<FhActenroll> fhActenrollList = fhActenrollService.listByMap(map);
			page.setTotal(fhActenrollList.size());
			int startIndex = (pageNo - 1) * pageSize;
			int endIndex = Math.min(startIndex + pageSize, fhActenrollList.size());
			if(startIndex<fhActenrollList.size()) {
				List<FhActenroll> subList = fhActenrollList.subList(startIndex, endIndex);
				page.setRecords(subList);
			}else {
				List<FhActenroll>  nullList= new ArrayList<>();
				page.setRecords(nullList);
			}
			return Result.OK(page);
		}
	}

	 @ApiOperation(value="日程报名-检查是否已报名", notes="日程报名-检查是否已报名")
	 //@RequiresPermissions("org.jeecg.modules:fh_challenge:add")
	 @PostMapping(value = "/CheckExists")
	 public Result<String> CheckExists(@RequestBody FhActenroll fhActenroll) {
//		 LambdaQueryWrapper<FhChallenroll> query = new LambdaQueryWrapper<FhChallenroll>();
//		 query.eq(FhChallenroll::getUserId, userId);
		 if(fhActenroll==null){
			 return Result.error("没有过滤参数！");
		 }
		 QueryWrapper queryWrapper = new QueryWrapper();
		 queryWrapper.eq("user_id", fhActenroll.getUserId());
		 queryWrapper.eq("parent_id", fhActenroll.getParentId());
		 List<FhActenroll> fhActenrollList = fhActenrollService.list(queryWrapper);
		 if(fhActenrollList!=null && fhActenrollList.size()>0){
			 return Result.error("用户已报名！");
		 }
		 return Result.OK("用户未报名！");
	 }



	 /**
	 *   添加
	 *
	 * @param fhActenroll
	 * @return
	 */
	@AutoLog(value = "日程报名-添加")
	@ApiOperation(value="日程报名-添加", notes="日程报名-添加")
	//@RequiresPermissions("org.jeecg.modules:fh_actenroll:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody FhActenroll fhActenroll) {
		if(oConvertUtils.isEmpty(fhActenroll.getUserId())){
			return Result.error("缺少报名用户信息！");
		}
		if(oConvertUtils.isNotEmpty(fhActenroll.getParentId())){
			FhActive fhActive =  fhActiveService.getById(fhActenroll.getParentId());
			if(oConvertUtils.isNotEmpty(fhActive.getStatus())&&fhActive.getStatus().equals("3")){
				if(oConvertUtils.isNotEmpty(fhActive.getSignEndtime())){
					if(DateUtils.getDate().compareTo(fhActive.getSignEndtime())>0){
						return Result.error("已超过报名时间！");
					}
				}
			}

			if(oConvertUtils.isNotEmpty(fhActive.getBeginTime()) && oConvertUtils.isNotEmpty(fhActive.getEndTime())){

				Map<String,Object> map = new HashMap<>();
				map.put("userId",fhActenroll.getUserId());
				map.put("beginTime",fhActive.getBeginTime());
				map.put("endTime",fhActive.getEndTime());
				List<FhActive> fhActiveList = fhActiveService.selectListForCheckDuplicateEnroll(map);
				for(FhActive fa:fhActiveList){
					if(fa.getIsroll()>0){
						return Result.error("您已报名时间重叠的活动，"+fa.getName()+",请检查！");
					}
				}
			}

			if(oConvertUtils.isNotEmpty(fhActive.getPeoples())&&fhActive.getPeoples()>0){
				QueryWrapper<FhActenroll> queryWrapper =  new QueryWrapper<>();
				queryWrapper.eq("parent_id",fhActenroll.getParentId());
				long count = fhActenrollService.count(queryWrapper);
				if(fhActive.getPeoples()<=count){
					return Result.error("已超出报名人数，联系管理员！");
				}
			}

		}


		fhActenrollService.save(fhActenroll);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param fhActenroll
	 * @return
	 */
	@AutoLog(value = "日程报名-编辑")
	@ApiOperation(value="日程报名-编辑", notes="日程报名-编辑")
	//@RequiresPermissions("org.jeecg.modules:fh_actenroll:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody FhActenroll fhActenroll) {
		fhActenrollService.updateById(fhActenroll);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "日程报名-通过id删除")
	@ApiOperation(value="日程报名-通过id删除", notes="日程报名-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:fh_actenroll:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//只限制小程序的端的取消报名
		if(!loginUser.getUsername().equals("admin")) {
			FhActenroll fhActenroll  = fhActenrollService.getById(id);
			FhActive fhActive =  fhActiveService.getById(fhActenroll.getParentId());
			if (oConvertUtils.isNotEmpty(fhActive.getStatus()) && fhActive.getStatus().equals("3")) {
				if (oConvertUtils.isNotEmpty(fhActive.getSignEndtime())) {
					if (DateUtils.getDate().compareTo(fhActive.getSignEndtime()) > 0) {
						return Result.error("不可取消，已超过报名时间！");
					}
				}
			}
		}
		fhActenrollService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *   通过active_id删除
	 *
	 * @param activeId
	 * @return
	 */
	@AutoLog(value = "日程报名-取消报名")
	@ApiOperation(value="日程报名-取消报名", notes="日程报名-取消报名")
	//@RequiresPermissions("org.jeecg.modules:fh_actenroll:delete")
	@DeleteMapping(value = "/cancel")
	public Result<String> cancel(@RequestParam(name="activeId",required=true) String activeId,
								 @RequestParam(name="userId",required=true) String userId) {
		QueryWrapper<FhActenroll> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("parent_id",activeId);
		queryWrapper.eq("user_id",userId);
		fhActenrollService.remove(queryWrapper);
		return Result.OK("取消成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "日程报名-批量删除")
	@ApiOperation(value="日程报名-批量删除", notes="日程报名-批量删除")
	//@RequiresPermissions("org.jeecg.modules:fh_actenroll:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fhActenrollService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "日程报名-通过id查询")
	@ApiOperation(value="日程报名-通过id查询", notes="日程报名-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<FhActenroll> queryById(@RequestParam(name="id",required=true) String id) {
		FhActenroll fhActenroll = fhActenrollService.getById(id);
		if(fhActenroll==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(fhActenroll);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fhActenroll
    */
    //@RequiresPermissions("org.jeecg.modules:fh_actenroll:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FhActenroll fhActenroll) {
		Integer isEnroll =1;//默认已报名
		if(oConvertUtils.isNotEmpty(fhActenroll.getIsEnroll())){
			isEnroll = fhActenroll.getIsEnroll()?1:0;
			fhActenroll.setIsEnroll(null);
		}
		// Step.1 组装查询条件
		QueryWrapper<FhActenroll> queryWrapper = QueryGenerator.initQueryWrapper(fhActenroll, request.getParameterMap());
		List<FhActenroll> exportList =new ArrayList<>();
		if(isEnroll==1) {//已报名
			  exportList = service.list(queryWrapper);
		}else{
			Map<String,Object> map = new HashMap<>();
			map.put("parentId",fhActenroll.getParentId());
			exportList= fhActenrollService.listByMap(map);
		}
		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.FILE_NAME, "未参赛人员");
		mv.addObject(NormalExcelConstants.CLASS, FhActenroll.class);
		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		ExportParams exportParams=new ExportParams("未参赛人员报表", "导出人:admin", "未参赛人员");

		exportParams.setImageBasePath(upLoadPath);
		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;

        //return super.exportXls(request, fhActenroll, FhActenroll.class, "日程报名");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("fh_actenroll:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FhActenroll.class);
    }


}
